/**
 * 管理系统-用户-接口路由模块
 */
 const express = require('express')
 const router = express.Router()
 
 /**
  * 引入其他模块
  */
const db = require('../../utils/db')
const md5 = require('blueimp-md5')
 
router.get('/api/user', (req, res, next) => {
  const sql = 'select * from ali_admin'
  db.query(sql, (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true,
      data: {
        list: result
      }
    })
  })
})

/**
 * 业务数据校验：
 *    邮箱是否重复
 *    昵称是否重复
 */
 router.get('/api/user/check/admin_email', (req, res, next) => {
  const sql = 'select * from ali_admin where admin_email = ?'
  db.query(sql, req.query.admin_email, (err, result) => {
    if (err) return next(err)
    res.send(result.length == 0)
  })
})

router.get('/api/user/check/admin_nickname', (req, res, next) => {
  const sql = 'select * from ali_admin where admin_nickname = ?'
  db.query(sql, req.query.admin_nickname, (err, result) => {
    if (err) return next(err)
    res.send(result.length == 0)
  })
})

router.post('/api/user/add', (req, res, next) => {
  const {admin_email, admin_slug, admin_nickname, admin_pwd} = req.body
  /**
   * 业务数据校验：
   *    邮箱是否重复
   *    昵称是否重复
   */
  let sql
  sql = 'select * from ali_admin where admin_email = ?'
  db.query(sql, admin_email, (err, result) => {
    if (err) return next(err)
    if (result.length > 0) {
      return res.status(200).json({
        success: false,
        msg: '邮箱已存在'
      })
    }
    
    sql = 'select * from ali_admin where admin_nickname = ?'
    db.query(sql, admin_nickname, (err, result) => {
      if (err) return next(err)
      if (result.length > 0) {
        return res.status(200).json({
          success: false,
          msg: '昵称已存在'
        })
      }

      sql = `insert into ali_admin 
              (admin_email, admin_slug, admin_nickname, admin_pwd) 
              values (?, ?, ?, ?)`
      db.query(sql, [admin_email, admin_slug, admin_nickname, md5(admin_pwd)], (err, result) => {
        if (err) return next(err)
        res.status(200).json({
          success: true,
          msg: '添加成功'
        })
      })
    })
  })
})
 
module.exports = router